import {Plugin, TransformResult} from 'vite';
import {createProcessor} from '@mdx-js/mdx';
import {createFilter, FilterPattern} from '@rollup/pluginutils';

interface Options {
  include?: FilterPattern,
  exclude?: FilterPattern
}

console.log('createProcessor:',createProcessor);

export default (options:Options = {}): Plugin => {
  return {
    name: 'vite-mdx',

    transform(code: string, id: string, ssr?: boolean): Promise<TransformResult> | TransformResult {
      const {
        include = /\.mdx/,
        exclude
      } = options;
      const filter = createFilter(include,exclude);

      if(filter(id)){
        console.log('pre vite-mdx code:',code);
        const processor = createProcessor({
          //必须设置为true, 保留jsx, 交给我们后面的 @vitejs/plugin-vue-jsx 去解析, 我们这里只解析markdown相关的语法 (因为默认生成的虚拟dom的方式是适配react的 不适用于vue)
          jsx: true,

          /** 改变生成的pragma指令注释*/
          //因为我们想自动在mdx文件的顶部加入 → import mdx from "vite-mdx/vue3"; 这么一句
          //故需要下面三个配置项
          jsxRuntime: 'classic',
          //除↑↑此之外, pragma参数还会影响我们生成的标识符
          //When in the classic runtime, this is used as an identifier for function calls: <x /> to React.createElement('x')
          pragma: 'mdx',
          pragmaImportSource: 'vite-mdx/vue3'
        });
        const result = `${processor.processSync(code).toString()}`;
        console.log('after vite-mdx code:',result.toString());

        return {
          code:  result,
          map: undefined
        }
      }
    }

  }
};
